import Router from 'koa-router';
import { ResponseUtil } from '../utils';
import { db } from '../models';

const router = new Router();

/**
 * 基础健康检查
 */
router.get('/', async (ctx) => {
  ctx.body = ResponseUtil.success(ctx, {
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    environment: process.env.NODE_ENV || 'development',
    version: process.env.npm_package_version || '1.0.0'
  }, '服务运行正常');
});

/**
 * 详细健康检查
 */
router.get('/detailed', async (ctx) => {
  try {
    const startTime = Date.now();

    // 检查数据库连接
    const dbConnectionStart = Date.now();
    await db.query('SELECT 1');
    const dbConnectionTime = Date.now() - dbConnectionStart;

    // 检查内存使用情况
    const memoryUsage = process.memoryUsage();

    // 检查CPU使用情况
    const cpuUsage = process.cpuUsage();

    const responseTime = Date.now() - startTime;

    ctx.body = ResponseUtil.success(ctx, {
      status: 'ok',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      environment: process.env.NODE_ENV || 'development',
      version: process.env.npm_package_version || '1.0.0',
      responseTime,
      checks: {
        database: {
          status: 'ok',
          responseTime: `${dbConnectionTime}ms`
        },
        memory: {
          rss: `${Math.round(memoryUsage.rss / 1024 / 1024)}MB`,
          heapTotal: `${Math.round(memoryUsage.heapTotal / 1024 / 1024)}MB`,
          heapUsed: `${Math.round(memoryUsage.heapUsed / 1024 / 1024)}MB`,
          external: `${Math.round(memoryUsage.external / 1024 / 1024)}MB`
        },
        cpu: {
          user: cpuUsage.user,
          system: cpuUsage.system
        }
      }
    }, '详细健康检查完成');
  } catch (error) {
    console.error('健康检查失败:', error);
    ctx.status = 503;
    ctx.body = ResponseUtil.error(ctx, '健康检查失败', 'HEALTH_CHECK_FAILED', 503);
  }
});

/**
 * 数据库健康检查
 */
router.get('/db', async (ctx) => {
  try {
    const startTime = Date.now();

    // 执行简单查询测试数据库连接
    await db.query('SELECT 1');

    // 检查表是否存在
    const tables = await db.query(
      `SELECT table_name FROM information_schema.tables
       WHERE table_schema = DATABASE()`
    );

    const responseTime = Date.now() - startTime;

    ctx.body = ResponseUtil.success(ctx, {
      status: 'ok',
      timestamp: new Date().toISOString(),
      responseTime: `${responseTime}ms`,
      tables: tables.map((row: any) => row.table_name)
    }, '数据库连接正常');
  } catch (error) {
    console.error('数据库健康检查失败:', error);
    ctx.status = 503;
    ctx.body = ResponseUtil.error(ctx, '数据库连接失败', 'DATABASE_CONNECTION_FAILED', 503);
  }
});

/**
 * 就绪检查
 */
router.get('/ready', async (ctx) => {
  try {
    // 检查所有关键依赖是否就绪
    await db.query('SELECT 1');

    ctx.body = ResponseUtil.success(ctx, {
      status: 'ready',
      timestamp: new Date().toISOString()
    }, '服务已就绪');
  } catch (error) {
    console.error('就绪检查失败:', error);
    ctx.status = 503;
    ctx.body = ResponseUtil.error(ctx, '服务未就绪', 'SERVICE_NOT_READY', 503);
  }
});

/**
 * 存活检查
 */
router.get('/live', async (ctx) => {
  ctx.body = ResponseUtil.success(ctx, {
    status: 'alive',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  }, '服务存活');
});

export default router;